/**
 * 请求验证中间件
 * 验证API请求的有效性
 */
const { ApiError } = require('./errorHandler');

const validator = {
  /**
   * 验证请求体中的必填字段
   * @param {string[]} requiredFields - 必填字段数组
   * @returns {Function} Express中间件
   */
  validateRequired: (requiredFields) => {
    return (req, res, next) => {
      const missingFields = [];
      
      for (const field of requiredFields) {
        if (req.body[field] === undefined || req.body[field] === null || req.body[field] === '') {
          missingFields.push(field);
        }
      }
      
      if (missingFields.length > 0) {
        return next(new ApiError(
          `缺少必填字段: ${missingFields.join(', ')}`, 
          400, 
          { missingFields }
        ));
      }
      
      next();
    };
  },
  
  /**
   * 验证ID参数是否为有效的数字
   * @returns {Function} Express中间件
   */
  validateIdParam: (paramName = 'id') => {
    return (req, res, next) => {
      const id = req.params[paramName];
      
      if (!id || isNaN(parseInt(id))) {
        return next(new ApiError(`无效的${paramName}参数`, 400));
      }
      
      // 将ID参数转换为数字
      req.params[paramName] = parseInt(id);
      next();
    };
  },
  
  /**
   * 验证日期字段是否为有效日期
   * @param {string[]} dateFields - 日期字段数组
   * @returns {Function} Express中间件
   */
  validateDates: (dateFields) => {
    return (req, res, next) => {
      const invalidFields = [];
      
      for (const field of dateFields) {
        if (req.body[field]) {
          const date = new Date(req.body[field]);
          
          if (isNaN(date.getTime())) {
            invalidFields.push(field);
          } else {
            // 转换为ISO格式的日期字符串
            req.body[field] = date.toISOString();
          }
        }
      }
      
      if (invalidFields.length > 0) {
        return next(new ApiError(
          `无效的日期字段: ${invalidFields.join(', ')}`, 
          400, 
          { invalidFields }
        ));
      }
      
      next();
    };
  }
};

module.exports = validator; 